# coding = utf-8

from django.db.models import Q
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet

from base.models import Category
from store.api.mobile.mobile_serializers import MobileGoodsStockSerializer

from store.models import GoodsStock


class MobileGoodsStockViewSet(ModelViewSet):
    """商品库存"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = GoodsStock.objects.all()
    serializer_class = MobileGoodsStockSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)
        # help_code = self.request.query_params.get("help_code", None)
        cate_id = self.request.query_params.get("cate_id", None)
        parent_id = self.request.query_params.get("parent_id", None)
        house_id = self.request.query_params.get("house", None)

        if house_id:
            queryset = queryset.filter(house_id=int(house_id))

        if parent_id:
            if parent_id != "-1":
                items = Category.objects.filter(Q(path__contains=parent_id) | Q(id=int(parent_id))).values_list("id", flat=True)
                queryset = queryset.filter(goods__cate_id__in=list(items))
        elif cate_id:
            queryset = queryset.filter(goods__cate_id=int(cate_id))

        if name:
            queryset = queryset.filter(Q(goods__name__contains=name) | Q(goods__help_code__contains=name.upper()))

        return queryset


